package com.ck.common.controller;

import com.ck.common.service.RoleService;
import com.ck.constant.RequestConstant;
import com.ck.constant.ResponseConstant;
import com.ck.exception.ControllerException;
import com.ck.exception.ServiceException;
import com.ck.model.common.Role;
import com.ck.model.common.User;
import com.ck.model.common.page.PageInfo;
import com.ck.model.common.sys.JsonResponse;
import com.ck.model.common.vo.RoleListVO;
import com.ck.util.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.rmi.ServerException;
import java.util.HashMap;
import java.util.List;

import static com.ck.util.StringUtils.listToFormatString;

/**
 * @author dxy
 * @date 2018/6/22 11:37
 */
@Controller
@RequestMapping("/role")
public class RoleController {
	private static Logger logger = LoggerFactory.getLogger(RoleController.class);
	@Autowired
	private RoleService roleService;

	/**
	 * 保存角色
	 */
	@ResponseBody
	@RequestMapping("/save")
	public Object saveRole(Role role, String moduleIds, HttpServletRequest request) {
		String roleName = role.getRoleName();
		if (StringUtils.isBlank(roleName)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "角色名称不能为空");
		}
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		String companyCode = loginUser.getCompanyCode();
		//验证角色是否存在
		Role oldRole = roleService.getRoleByRoleName(companyCode, roleName);
		if (oldRole != null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "角色名称已存在，请重新输入角色名称");
		}
		try {
			roleService.insertRole(role, moduleIds, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("RoleController saveRole 保存角色失败：" + e.getMessage());
			return new ControllerException("保存角色失败： " + e.getMessage());
		}
		return "";
	}

	/**
	 * 保存角色
	 */
	@ResponseBody
	@RequestMapping("/update")
	public Object updateRole(Role role, String moduleIds, HttpServletRequest request) {
		//验证角色ID是否存在
		Long roleId = role.getRoleId();
		if (roleId == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "角色主键为空，请联系管理员");
		}
		//验证角色名称是否存在
		String roleName = role.getRoleName();
		if (StringUtils.isBlank(roleName)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "角色名称不能为空");
		}
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		String companyCode = loginUser.getCompanyCode();
		//验证角色是否存在
		Role oldRole = roleService.getRoleByRoleName(companyCode, roleName);
		if (oldRole != null) {
			if (!oldRole.getRoleName().equals(roleName)) {
				return new JsonResponse(ResponseConstant.CODE_FAIL, "角色名称已存在，请重新输入角色名称");
			}
		}
		try {
			roleService.updateRole(role, moduleIds, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("RoleController saveRole 保存角色失败：" + e.getMessage());
			return new ControllerException("保存角色失败： " + e.getMessage());
		}
		return "";
	}

	/**
	 * 角色列表
	 */
	@RequestMapping("/list")
	public String listRole(Integer status, String roleName, Integer pageNum, Integer pageSize, Model model, HttpServletRequest request) {
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		String companyCode = loginUser.getCompanyCode();
		try {
			PageInfo<RoleListVO> pageInfo = roleService.listRole(companyCode, status, roleName, pageNum, pageSize);
			model.addAttribute("companyCode", companyCode);
			model.addAttribute("status", status);
			model.addAttribute("roleName", roleName);
			model.addAttribute("roleList", pageInfo.getList());
			model.addAttribute("pageNum", pageInfo.getPageNum());
			model.addAttribute("pageSize", pageInfo.getPageSize());
			model.addAttribute("total", pageInfo.getTotal());
		} catch (ServerException e) {
			e.printStackTrace();
			logger.error("RoleController listRole 获取角色列表失败：" + e.getMessage());
		}
		return "common/role_list";
	}

	/**
	 * 获取角色选择列表
	 */
	@ResponseBody
	@RequestMapping("/listRoleSelect")
	public Object listRoleSelect(HttpServletRequest request) {
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		try {
			return roleService.listRoleSelect(loginUser.getCompanyCode());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("RoleController listRoleSelect 获取角色选择列表失败：" + e.getMessage());
			return new ControllerException("获取角色选择列表失败： " + e.getMessage());
		}
	}

	/**
	 * 启用禁用角色
	 */
	@ResponseBody
	@RequestMapping(value = "/enableDisableRole", method = RequestMethod.POST)
	public Object enableDisableRole(Role role, HttpServletRequest request) {
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		String ip = HttpUtils.getRemortIP(request);
		if (role.getRoleId() == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "角色ID不能为空，请联系管理员");
		}
		try {
			roleService.enableDisableRole(role, loginUser, ip);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("RoleController enableDisableRole 启用禁用角色失败：" + e.getMessage());
			return new ControllerException("启用禁用角色失败： " + e.getMessage());
		}
		return "";
	}

	/**
	 * 跳转至选择权限
	 *
	 * @return
	 */
	@RequestMapping(value = "/goAuthPicker")
	public String goAuthPicker(Long roleId, Model model) {
		model.addAttribute("roleId", roleId);
		return "common/auth_picker";
	}

	/**
	 * 获取角色拥有的权限和id
	 */
	@ResponseBody
	@RequestMapping(value = "/listModuleNamesByRoleId")
	public Object listModuleNamesByRoleId(Long roleId) {
		if (roleId == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "角色ID不能为空，请联系管理员");
		}
		try {
			HashMap<String,String> resultMap = new HashMap<>(2);
			String authName = listToFormatString(roleService.listModuleNamesByRoleId(roleId), ",");
			resultMap.put("authName",authName);
			List<String> moduleIdList = roleService.listModuleIdsByRoleId(roleId);
			String authId = listToFormatString(moduleIdList,",");
			resultMap.put("authId",authId);
			return resultMap;
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error("RoleController listModuleNamesByRoleId 获取角色拥有的权限名称失败：" + e.getMessage());
			return e;
		}
	}

}
